package com.elephant.config;

import com.elephant.dao.EmployeeDao;
import com.elephant.pojo.Employee;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLOutput;
import java.util.Arrays;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    EmployeeDao employeeDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();
        String power =employee.getPower();
        if(power==null) {
            power="null";
        }
        String[] powers = power.split(",");
        for (String s : powers) {
            info.addStringPermission(s);
            System.out.println("执行了授权doGetAuthorizationInfo,授予"+s+"权限");
        }
        //info.addStringPermissions(Arrays.asList(powers));


        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证doGetAuthenticationInfo");

        UsernamePasswordToken token1 = (UsernamePasswordToken)token;
        Employee employee = employeeDao.getEmployeeByName(token1.getUsername());
        System.out.println(employee.toString());
        String name = employee.getLastName();
        if (null==employee) {
            return null;
        }
        return new SimpleAuthenticationInfo(employee,employee.getId().toString(),"");
    }
}
